package com.sinotn.ks.node.camera.spi;

import java.io.File;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.sinotn.Page;
import com.sinotn.SinotnLogger;
import com.sinotn.error.MessageException;
import com.sinotn.ks.definition.DataUploader;
import com.sinotn.ks.definition.ExamPlugin;
import com.sinotn.ks.node.camera.dao.CameraPhotoDao;
import com.sinotn.ks.node.camera.dao.cond.CameraPhotoCond;
import com.sinotn.ks.node.camera.service.CameraService;
import com.sinotn.ks.node.camera.vo.CameraPhotoVO;

public class CameraDataUploader implements DataUploader,ExamPlugin {
	private int order = 1;
	@Autowired
	private CameraPhotoDao cameraDao;
	@Autowired
	private CameraService service;

	public CameraDataUploader() {
	}

	@Override
	public int getOrder() {
		return this.order;
	}

	public void setOrder(int order) {
		this.order = order;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void exportRoom(File folder, String roomId,String roundId) {
		PrintWriter pw = null;
		try {
			Set<String> roomIdSets = new HashSet<String>();
			roomIdSets.add(roomId);
			CameraPhotoCond cond = new CameraPhotoCond();
			cond.addRoomId(roomId);
			// 分页处理
			int pageIdx = 1; // 从第一页开始查询
			int pageSize = 100; // 每一页100条记录
			Page page = cameraDao.selectCameraPhotoByPage(pageIdx, pageSize, cond);
			int totalPage = page.getTotalPageNum(); // 总共有几页
			if(totalPage>0){
				List<CameraPhotoVO> photos = page.getRows();
				File file = new File(folder, "cameraPhoto.xml");
				pw = new PrintWriter(file, "UTF-8");
				pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
				pw.append("<data>");
				while (true) {
					if (photos != null && photos.size() > 0) {
						for (CameraPhotoVO vo : photos) {
							// 将数据添加到XML
							this.render(pw, vo);
						}
					} else {
						break;
					}
					// 删除数据库中的照片
					cameraDao.deleteMultiPhotos(photos);
					pageIdx++;
					if (pageIdx <= totalPage) {
						page = cameraDao.selectCameraPhotoByPage(pageIdx, pageSize, cond);
						photos = page.getRows();
					} else {
						break;
					}
				}
				pw.append("</data>");
				pw.flush();

				// 发送消息给客户端，将警告消息清零
				service.sendWarnCountToComputer();
			}
		} catch (Throwable e) {
			SinotnLogger.DEBUG.error("导出考场摄像监考记录发生系统错误:", e);
			throw new MessageException("导出考场摄像监考记录发生系统错误");
		} finally {
			if (pw != null) {
				pw.close();
			}
		}
	}

	/**
	 * 封装数据到XML
	 * @param pw
	 * @param cameraVo
	 * @auth <a href="mailto:liyunfeng@sinotn.com">李云峰</a>
	 * @date 2017年7月13日 下午5:14:34
	 */
	private void render(PrintWriter pw, CameraPhotoVO cameraVo) {
		pw.append("<cameraPhoto>");
		pw.append("<roomId>").append(cameraVo.getRoomId()).append("</roomId>");// 考场ID
		pw.append("<examineeId>").append(cameraVo.getExamineeId()).append("</examineeId>");// 考生ID
		pw.append("<answerPaperId>").append(handleNullValue(cameraVo.getAnswerPaperId())).append("</answerPaperId>");// 试卷ID
		pw.append("<examineeName><![CDATA[").append(cameraVo.getExamineeName()).append("]]></examineeName>");// 考生姓名
		pw.append("<examInfoId>").append(cameraVo.getExamInfoId()).append("</examInfoId>");
		pw.append("<fixed>").append(String.valueOf(cameraVo.getFixed())).append("</fixed>");
		pw.append("<state>").append(String.valueOf(cameraVo.getState())).append("</state>");
		pw.append("<phase>").append(String.valueOf(cameraVo.getPhase())).append("</phase>");
		pw.append("<similar>").append(String.valueOf(cameraVo.getSimilar())).append("</similar>");
		pw.append("<faceCount>").append(String.valueOf(cameraVo.getFaceCount())).append("</faceCount>");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		pw.append("<createTime>").append(sdf.format(cameraVo.getCreateTime())).append("</createTime>");// 拍照时间(yyyy-MM-dd HH:mm:ss)
		pw.append("<invigilatorName><![CDATA[").append(handleNullValue(cameraVo.getInvigilatorName())).append("]]></invigilatorName>");// 监考员姓名
		pw.append("<invigilatorPhone><![CDATA[").append(handleNullValue(cameraVo.getInvigilatorPhone())).append("]]></invigilatorPhone>");// 监考员电话
		pw.append("<remark><![CDATA[").append(handleNullValue(cameraVo.getRemark())).append("]]></remark>");// 备注
		pw.append("<photoPath>").append(cameraVo.getPhotoPath()).append("</photoPath>");// 照片
		pw.append("</cameraPhoto>");
	}

	/**
	 * 处理null值
	 * @param value
	 * @return
	 * @auth <a href="mailto:liyunfeng@sinotn.com">李云峰</a>
	 * @date 2017年7月17日 下午6:36:46
	 */
	private String handleNullValue(String value) {
		if (!StringUtils.isNotBlank(value)) {
			return "";
		} else {
			return value;
		}
	}

	@Override
	public List<String> getConsoleOperateButtons() {
		ArrayList<String> list=new ArrayList<String>(1);
		list.add("<span class=\"glyphicon glyphicon-picture\" biz-id=\"room/plugin/camera/handle#viewPhoto\"></span>");
		return list;
	}
}
